<?php
/*
 * (C) Copyright 2013 Torsten Gorath (http://www.blauesdach.de/).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 *     Torsten Gorath
 */
require_once $basedir."/inc/table.php";

class Lock extends table {
	private $table = "";
	private $id = "";
	private $user = "";
	private $since = "";
	
	static public function isLocked($table, $id) {
	    global $VEREIN;
		$query = "SELECT * FROM " . $VEREIN['prefix'] . "lock WHERE table='".$table."' AND id='".$id."' AND NOW() < ADDTIME(since, '00:30:00')";
		$locks = Database::getDefault()->execute($query, "Lock");
		if(size($locks)>0) return true;
		return false;
	}
	
	static public function hasLock($table, $id, $user) {
	    global $VEREIN;
		$query = "SELECT * FROM Lock WHERE table='" . $VEREIN['prefix'] . $table . "' AND id='".$id."' AND user='".$user."' AND NOW() < ADDTIME(since, '00:30:00')";
		$locks = Database::getDefault()->execute($query, "Lock");
		if(size($locks)>0) return true;
		return false;
	}
	
	static public function getLock($table, $id, $user) {
	    global $VEREIN;
		if(Lock::hasLock($table, $id, $user)) return true;
		if(Lock::isLocked($table, $id)) return false;
		$query = "INSERT INTO " . $VEREIN['prefix'] . "lock (table, id, user, since) VALUES ('$table', '$id', '$user', NOW())";
		Database::getDefault()->query($query);
		return true;
	}
	
	static public function releaseLock($table, $id, $user) {
	    global $VEREIN;
		if(!Lock::hasLock($table, $id, $user)) return false;
		$query = "DELETE FROM " . $VEREIN['prefix'] . "lock WHERE table='$table' AND id='$id' AND user='$user'";
		Database::getDefault()->query($query);
		return true;
	}
	
}
?>